package com.cjst.controller.api.subjects;

import java.io.File;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cjst.pojo.subject.SubjectsAnswer;
import com.alibaba.dubbo.container.Main;
import com.cjst.pojo.subject.QuestAnswer;
import com.cjst.pojo.subject.QuestClassHistory;
import com.cjst.pojo.subject.SubjectsHistory;
import com.cjst.pojo.sys.FileInfo;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.subject.ExamResultService;
import com.cjst.service.subject.QuestAnswerService;
import com.cjst.service.subject.QuestClassHistoryService;
import com.cjst.service.subject.SubjectsAnswerService;
import com.cjst.service.subject.SubjectsHistoryService;
import com.cjst.service.sys.FileInfoService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.common.DateUtil;
import com.cjst.util.common.GenerativeToken;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;
@Controller
@RequestMapping("api/questClass")
public class QuestClassController {
	private static Logger log = Logger.getLogger(QuestClassController.class);
//	@Autowired
//	private SubjectsService subjectsService;
//	@Autowired
//	private QuestClassService questClassService;
	
	@Autowired
	private SubjectsHistoryService subjectsHistoryService;
	@Autowired
	private QuestClassHistoryService questClassHistoryService;
	
	@Autowired
	private QuestAnswerService questAnswerService;
	@Autowired
	private SubjectsAnswerService subjectsAnswerService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private ExamResultService examResultService;
	
	@Value("${img.location}")
	private String fileUploadPath;
	@Value("${file.path}")
	private String filePath;
	
	@Autowired
	private FileInfoService fileInfoService;
	
	@Value("${file.path}")
	private String begin_url;
	
	
	/**
	 * 不分页了，反正数据少
	 * @param date  format "2020-01-12","yyyy-mm-dd"
	 * @return
	 */
	@RequestMapping(value = "/getExamineByDateAndExamineType", method = RequestMethod.POST)
	@ResponseBody
	public String getExamineByDateAndExamineType(String date,int examineType) {
		
		if(date==null) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION,"error",0);
			
			return obj.toString();
		}
//		if(examineType==null) {
//			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION,"error",0);
//			
//			return obj.toString();
//		}
		
		WherePrams wherePrams=Method.where("isDelete", C.EQ, 0);
		
		if (examineType == 0) {
			wherePrams.and("createTime", C.DAEQ, getWeekBegin(date));//周日为一星期第一天
			wherePrams.and("createTime", C.IXAOEQ, getWeekEnd(date));//周六为一星期最后一天
		}
		else if (examineType == 1) {
			wherePrams.and("createTime", C.DAEQ, getMonthBegin(date));//周日为一星期第一天
			wherePrams.and("createTime", C.IXAOEQ, getMonthEnd(date));//周六为一星期最后一天
		}
		else if (examineType == 2) {
			wherePrams.and("createTime", C.DAEQ, getMonthBegin(date));//周日为一星期第一天
			wherePrams.and("createTime", C.IXAOEQ, getMonthEnd(date));//周六为一星期最后一天
		}
		else if (examineType == 3) {
			wherePrams.and("createTime", C.DAEQ, getMonthBegin(date));//周日为一星期第一天
			wherePrams.and("createTime", C.IXAOEQ, getMonthEnd(date));//周六为一星期最后一天
		}else {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION,"错误examineType",0);
			
			return obj.toString();
		}
		

		
		
		wherePrams.and("examineType", C.EQ, examineType);
		
		List<QuestClassHistory> questClassHistoryList=questClassHistoryService.list(wherePrams);
		
		if(questClassHistoryList==null||questClassHistoryList.size()==0) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS,"无记录",0);
			
			return obj.toString();
		}
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS,"success",questClassHistoryList);
		
		return obj.toString();
	}
	
	
	
	@RequestMapping(value = "getExamineDetailById", method = RequestMethod.POST)
	@ResponseBody
	public String getExamineDetailById(String id) {
		if(id==null||id.length()<5) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "参数错误", 0);
			return obj.toString();
		}
		
		
		QuestClassHistory questClassHistory=questClassHistoryService.get(id);
		
		if(questClassHistory==null) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "无结果", 0);
			return obj.toString();
		}
		
		
		WherePrams wheres2=Method.where("isDelete", C.EQ, 0);
		//wheres2.and("status", C.EQ, 0);
		wheres2.and("catagoryId", C.EQ, id);
		wheres2.orderBy(" create_time desc");
		
		List<SubjectsHistory> subjectsHistoryList=subjectsHistoryService.list(wheres2); 
		
		//根据考核项目给各个题目分类，形成LIST数组
		Map<String,List<SubjectsHistory>> subjectsHistoryList_classify=new HashMap<String ,List<SubjectsHistory>>();
		if (subjectsHistoryList != null) {
			for (int i = 0; i < subjectsHistoryList.size(); i++) {
				SubjectsHistory tmp = subjectsHistoryList.get(i);
				if (tmp.getAnswer() != null && !"".equals(tmp.getAnswer())) {
					if (subjectsHistoryList_classify.containsKey(tmp.getAnswer())) {
						subjectsHistoryList_classify.get(tmp.getAnswer()).add(tmp);
					} else {
						List<SubjectsHistory> list = new ArrayList<SubjectsHistory>();
						list.add(tmp);
						subjectsHistoryList_classify.put(tmp.getAnswer(), list);
					}
				}
			}
		}
		
		List<SubjectJsonPojo> tmp=new ArrayList<SubjectJsonPojo>();
		subjectsHistoryList_classify.keySet().forEach(one->{
			SubjectJsonPojo subjectJsonPojo=new SubjectJsonPojo();
			subjectJsonPojo.setExamineType(one);
			subjectJsonPojo.setSubjects(subjectsHistoryList_classify.get(one));
			tmp.add(subjectJsonPojo);
		});
		
		WherePrams where3=Method.where("isDelete", C.EQ, 0);
		where3.and("questId", C.EQ, id);
		
		
		List<QuestAnswer> questAnswerList=questAnswerService.list(where3);
		List<SubjectsAnswer> subjectsAnswerList=subjectsAnswerService.list(where3);
		
		
		Map<Integer,List<QuestAnswer>> questAnswerMap=new HashMap<Integer,List<QuestAnswer>>();
		questAnswerList.forEach(one->{
			if(!questAnswerMap.containsKey(one.getStatus())) {
				questAnswerMap.put(one.getStatus(), new ArrayList<QuestAnswer>());
			}
			questAnswerMap.get(one.getStatus()).add(one);
		});
		
		
		Map<Integer,List<SubjectsAnswer>> subjectsAnswerMap=new HashMap<Integer,List<SubjectsAnswer>>();
		subjectsAnswerList.forEach(one->{
			if(!subjectsAnswerMap.containsKey(one.getStatus())) {
				subjectsAnswerMap.put(one.getStatus(), new ArrayList<SubjectsAnswer>());
			}
			subjectsAnswerMap.get(one.getStatus()).add(one);
		});
		
		
		
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("subjectsList", tmp);
		result.put("questClass", questClassHistory);
		if(questAnswerMap!=null) {
			result.put("questAnswerMap", questAnswerMap);
		}
		if(subjectsAnswerList!=null&&subjectsAnswerList.size()>0) {
			result.put("subjectsAnswerMap", subjectsAnswerMap);
		}
		
		
		ResultObj obj=new ResultObj(ResultCode.STATE_SUCCESS, "success", result);
		return obj.toString();
	}
	
	/**
	 * 公园方专用
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/answerAssess", method = RequestMethod.POST)
	@ResponseBody
	public String answerAssess(@RequestBody AnswerVO data) {
		
		if(!isPark()) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "非公园方账号", null);
			return obj.toString();
		}
		
		if(data==null) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		
		log.info("answerAssess------data:"+data.toString());
		
		QuestAnswerVO questClass=data.getQuestClass();
		
		String questClassId=questClass.getId();
		int abarbeitung=questClass.getAbarbeitung();
		
		QuestClassHistory history=questClassHistoryService.get(questClassId);
		
		//检查改表考核流程状态
		if(history.getStatus()>=1) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "已被考核过", null);
			return obj.toString();
		}
		
		
		List<SubjectsAnswer> subjectAnswerList=new ArrayList<SubjectsAnswer>();
		
		List<SubjectAnswerVO> subjectList=data.getSubjectList();
		for(int i=0;i<subjectList.size();i++) {
			SubjectAnswerVO subjectAnswerVO=subjectList.get(i);
			String subjectId=subjectAnswerVO.getId();
			
			SubjectsAnswer subjectsAnswer=new SubjectsAnswer();
			subjectsAnswer.setId(GenerativeToken.getToken().toUpperCase());
			subjectsAnswer.setQuestId(questClassId);
			subjectsAnswer.setSubjectId(subjectId);
			subjectsAnswer.setOptions(subjectAnswerVO.getOptions());
			subjectsAnswer.setImgs(subjectAnswerVO.getImgs()==null ?null:subjectAnswerVO.getImgs().toString());
			subjectsAnswer.setScore(subjectAnswerVO.getScore());
			subjectsAnswer.setStatus(1);//考核
			
			subjectAnswerList.add(subjectsAnswer);
		}
		log.info("questClass:"+questClass.toString());
		log.info("subjectList:"+subjectList.toString());
		log.info("subjectAnswerList:"+subjectAnswerList.toString());
		
		QuestAnswer questAnswer=new QuestAnswer();
		questAnswer.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		questAnswer.setQuestId(questClassId);
		questAnswer.setAbarbeitung(abarbeitung);
		questAnswer.setStatus(1);//考核
		//questAnswer.setTotalDeduct(totalDeduct);
		String questAnswerResult=questAnswerService.addLocalByid(questAnswer);
		int subjectsAnswerResult=subjectsAnswerService.addList(subjectAnswerList);
		
		
//		subjectList.forEach(tmp->{
//			List<String> imgs=tmp.getImgs();
//			if(imgs!=null&&imgs.size()>0) {
//				String subjectId=tmp.getId();
//				fileInfoService.updateList(subjectId,imgs);
//			}
//			
//		});
		
		
		history.setStatus(1);//考核已提交
		questClassHistoryService.update(history);
		
		Map<String,String> resultMap=new HashMap<String,String>();
		resultMap.put("questAnswerResult", questAnswerResult);
		resultMap.put("subjectsAnswerResult", String.valueOf(subjectsAnswerResult));
		
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", resultMap);
		return obj.toString();
	}
	
	/*
	@RequestMapping(value = "/answerAssess", method = RequestMethod.POST)
	@ResponseBody
	public String answerAssess(String jsonString) {
		if(jsonString==null||"".equals(jsonString)) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		log.info("answerAssess------jsonString:"+jsonString);
		
		JSONObject json=JSONObject.parseObject(jsonString);
		JSONObject questClass=json.getJSONObject("questClass");
		
		String questClassId=questClass.getString("id");
		int abarbeitung=questClass.getIntValue("abarbeitung");
		
		List<SubjectsAnswer> subjectAnswerList=new ArrayList<SubjectsAnswer>();
		
		JSONArray subjectList=json.getJSONArray("subjectList");
		for(int i=0;i<subjectList.size();i++) {
			JSONObject subject=subjectList.getJSONObject(i);
			String subjectId=subject.getString("id");
			//JSONObject result=subject.getJSONObject("result");
			
			String options=subject.getString("options");
			float score=subject.getFloatValue("score");
			String imgs=subject.getString("imgs");
			
			SubjectsAnswer subjectsAnswer=new SubjectsAnswer();
			subjectsAnswer.setId(GenerativeToken.getToken().toUpperCase());
			subjectsAnswer.setQuestId(questClassId);
			subjectsAnswer.setSubjectId(subjectId);
			subjectsAnswer.setOptions(options);
			subjectsAnswer.setImgs(imgs);
			subjectsAnswer.setScore(score);
			subjectsAnswer.setStatus(1);//考核
			
			subjectAnswerList.add(subjectsAnswer);
		}
		log.info("questClass:"+questClass.toJSONString());
		log.info("subjectList:"+subjectList.toJSONString());
		log.info("subjectAnswerList:"+subjectAnswerList.toString());
		
		QuestAnswer questAnswer=new QuestAnswer();
		questAnswer.setQuestId(questClassId);
		questAnswer.setAbarbeitung(abarbeitung);
		questAnswer.setStatus(1);//考核
		//questAnswer.setTotalDeduct(totalDeduct);
		String questAnswerResult=questAnswerService.addLocalByid(questAnswer);
		int subjectsAnswerResult=subjectsAnswerService.addList(subjectAnswerList);
		
		Map<String,String> resultMap=new HashMap<String,String>();
		resultMap.put("questAnswerResult", questAnswerResult);
		resultMap.put("subjectsAnswerResult", String.valueOf(subjectsAnswerResult));
		
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", resultMap);
		return obj.toString();
	}
	*/
	
	
	//整改，
	/**
	 * 服务方专用
	 * @param data
	 * @return
	 */
	
	@RequestMapping(value = "/answerAbarbeitung", method = RequestMethod.POST)
	@ResponseBody
	public String answerAbarbeitung(@RequestBody AnswerVO data) {
		
		if(!isService()) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "非服务方账号", null);
			return obj.toString();
		}
		
		if(data==null) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "error", null);
			return obj.toString();
		}
		
		log.info("answerAssess------data:"+data.toString());
		
		QuestAnswerVO questClass=data.getQuestClass();
		
		String questClassId=questClass.getId();
		int abarbeitung=questClass.getAbarbeitung();
		
		QuestClassHistory history=questClassHistoryService.get(questClassId);
		
		//检查改表考核流程状态
		if(history.getStatus()<1) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "未经过考核流程", null);
			return obj.toString();
		}
		else if(history.getStatus()>=2) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "已被整改过", null);
			return obj.toString();
		}
		
		
		List<SubjectsAnswer> subjectAnswerList=new ArrayList<SubjectsAnswer>();
		
		List<SubjectAnswerVO> subjectList=data.getSubjectList();
		for(int i=0;i<subjectList.size();i++) {
			SubjectAnswerVO subjectAnswerVO=subjectList.get(i);
			String subjectId=subjectAnswerVO.getId();
			
			SubjectsAnswer subjectsAnswer=new SubjectsAnswer();
			subjectsAnswer.setId(GenerativeToken.getToken().toUpperCase());
			subjectsAnswer.setQuestId(questClassId);
			subjectsAnswer.setSubjectId(subjectId);
			subjectsAnswer.setOptions(subjectAnswerVO.getOptions());
			subjectsAnswer.setImgs(subjectAnswerVO.getImgs()==null ?null:subjectAnswerVO.getImgs().toString());
			subjectsAnswer.setScore(subjectAnswerVO.getScore());
			subjectsAnswer.setStatus(2);//整改
			
			subjectAnswerList.add(subjectsAnswer);
		}
		log.info("questClass:"+questClass.toString());
		log.info("subjectList:"+subjectList.toString());
		log.info("subjectAnswerList:"+subjectAnswerList.toString());
		
		QuestAnswer questAnswer=new QuestAnswer();
		questAnswer.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		questAnswer.setQuestId(questClassId);
		questAnswer.setAbarbeitung(abarbeitung);
		questAnswer.setStatus(2);//整改
		//questAnswer.setTotalDeduct(totalDeduct);
		String questAnswerResult=questAnswerService.addLocalByid(questAnswer);
		int subjectsAnswerResult=subjectsAnswerService.addList(subjectAnswerList);
		
		
//		subjectList.forEach(tmp->{
//			List<String> imgs=tmp.getImgs();
//			if(imgs!=null&&imgs.size()>0) {
//				String subjectId=tmp.getId();
//				fileInfoService.updateList(subjectId,imgs);
//			}
//			
//		});
		
		
		history.setStatus(2);//整改
		questClassHistoryService.update(history);
		
		Map<String,String> resultMap=new HashMap<String,String>();
		resultMap.put("questAnswerResult", questAnswerResult);
		resultMap.put("subjectsAnswerResult", String.valueOf(subjectsAnswerResult));
		
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", resultMap);
		return obj.toString();
	}
	
	
	/**
	 * 验收，公园方专用
	 * 
	 * @param data
	 * @return
	 */
	
	@RequestMapping(value = "/answerInspection", method = RequestMethod.POST)
	@ResponseBody
	public String answerInspection(@RequestBody AnswerVO data) {
		if(!isPark()) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "非公园方账号", null);
			return obj.toString();
		}
		
		
		QuestClassHistory history= questClassHistoryService.get(data.getQuestClass().getId());
		if(history.getStatus()<2) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "未经过考核活整改流程", null);
			return obj.toString();
		}
		else if(history.getStatus()>=3) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "已被验收整改过", null);
			return obj.toString();
		}
		
		QuestAnswer questAnswer=new QuestAnswer();
		questAnswer.setQuestId(data.getQuestClass().getId());
		questAnswer.setAbarbeitung(data.getQuestClass().getAbarbeitung());
		questAnswer.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		questAnswer.setStatus(3);//验收
		
		List<SubjectsAnswer> subjectAnswerList=new ArrayList<SubjectsAnswer>();
		data.getSubjectList().forEach(tmp->{
			SubjectsAnswer one=new SubjectsAnswer();
			one.setOptions(tmp.getOptions());
			one.setQuestId(data.getQuestClass().getId());
			one.setSubjectId(tmp.getId());
			one.setStatus(3);
			subjectAnswerList.add(one);
			
		});
		
		history.setStatus(3);
		
		questClassHistoryService.update(history);
		questAnswerService.addLocalByid(questAnswer);
		subjectsAnswerService.addList(subjectAnswerList);
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
		return obj.toString();
	}
	
	
	/**
	 * 公园方专用
	 * 巡查
	 * @param subjectAnswerVO
	 * @return
	 */
	@RequestMapping(value = "/publishPatrol", method = RequestMethod.POST)
	@ResponseBody
	public String publishPatrol(@RequestBody SubjectAnswerVO subjectAnswerVO) {
//		if(!isPark()) {
//			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "非公园方账号", null);
//			return obj.toString();
//		}
		
		if(subjectAnswerVO.getImgs()==null||subjectAnswerVO.getImgs().length()<1) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "no imgs", null);
			return obj.toString();
		}
		if(subjectAnswerVO.getContent()==null||subjectAnswerVO.getContent().length()<1) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "no content", null);
			return obj.toString();
		}
		
		SubjectsAnswer subjectsAnswer=new SubjectsAnswer();
		
		subjectsAnswer.setQuestId("PublishPatrol");
		//subjectsAnswer.setSubjectId(GenerativeToken.getToken().toUpperCase());
		subjectsAnswer.setImgs(subjectAnswerVO.getImgs()==null? null:subjectAnswerVO.getImgs().toString());
		subjectsAnswer.setContent(subjectAnswerVO.getContent());
		subjectsAnswer.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		subjectsAnswer.setStatus(1);
		
		String result=subjectsAnswerService.addLocalByid(subjectsAnswer);
		
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);
		return obj.toString();
	}
	
	
	/**
	 * 服务方专用 巡查回复
	 * @param subjectAnswerVO
	 * @return
	 */
	
	@RequestMapping(value = "/answerPatrol", method = RequestMethod.POST)
	@ResponseBody
	public String answerPatrol(@RequestBody SubjectAnswerVO subjectAnswerVO) {
//		if(!isService()) {
//			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "非服务公园方账号", null);
//			return obj.toString();
//		}
		
		if(subjectAnswerVO.getId()==null||subjectAnswerVO.getId().length()<5) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "error id", null);
			return obj.toString();
		}
//		if(subjectAnswerVO.getImgs()==null||subjectAnswerVO.getImgs().size()<1) {
//			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "no imgs", null);
//			return obj.toString();
//		}
		if(subjectAnswerVO.getContent()==null||subjectAnswerVO.getContent().length()<1) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "no content", null);
			return obj.toString();
		}
		
		SubjectsAnswer subjectsAnswer=subjectsAnswerService.get(subjectAnswerVO.getId());
		subjectsAnswer.setSubjectId(subjectAnswerVO.getId());
		subjectsAnswer.setImgs(subjectAnswerVO.getImgs()==null? null:subjectAnswerVO.getImgs().toString());
		subjectsAnswer.setContent(subjectAnswerVO.getContent());
		subjectsAnswer.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		subjectsAnswer.setStatus(2);
		
		String result=subjectsAnswerService.addLocalByid(subjectsAnswer);
		
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", null);
		return obj.toString();
	}

	
	/**
	 * 朋友圈
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getPatrolDetailById", method = RequestMethod.POST)
	@ResponseBody
	public String getPatrolDetailById(String id) {
		
		if(id==null||id.length()<5) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "error id", null);
			return obj.toString();
		}

		
		
		WherePrams wherePrams=Method.where("isDelete", C.EQ, 0);
		wherePrams.and("questId", C.EQ, "PublishPatrol");
		wherePrams.and("id", C.EQ, id);
		
		SubjectsAnswer subjectsAnswer= subjectsAnswerService.get(wherePrams);
		if(subjectsAnswer==null) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "no result", null);
			return obj.toString();
		}
		
		WherePrams wherePrams2=Method.where("isDelete", C.EQ, 0);
		wherePrams2.and("questId", C.EQ, "PublishPatrol");
		wherePrams2.and("subjectId", C.EQ, subjectsAnswer.getId());
		
		SubjectsAnswer subjectsAnswer2= subjectsAnswerService.get(wherePrams2);
		
		Map<Integer,SubjectsAnswer> result=new HashMap<Integer,SubjectsAnswer>();
		result.put(1, subjectsAnswer);
		if(subjectsAnswer2!=null) {
			result.put(2, subjectsAnswer2);
		}
		
		ResultObj obj=new ResultObj(ResultCode.RESULT_SUCCESS, "success", result);
		return obj.toString();
	}
	
	
	/**
	 * 朋友圈
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getPatrolByPage", method = RequestMethod.POST)
	@ResponseBody
	public String getPatrolByPage(int size, int page) {

		if (size < 1) {
			size = 10;
		}
		if (page < 1) {
			page = 1;
		}

		WherePrams wherePrams = Method.where("isDelete", C.EQ, 0);
		wherePrams.and("questId", C.EQ, "PublishPatrol");
		wherePrams.and("status", C.EQ, 1);

		// 获取全部status==1的巡查报告
		List<SubjectsAnswer> subjectsAnswerList = subjectsAnswerService.listPage(wherePrams,
				" ORDER BY create_time desc limit " + (page - 1) * size + "," + size);

		// 获取每个巡查报告的后续事件
		//status=2以后或许还有3,4,5等
		Map<String, List<SubjectsAnswer>> result = new HashMap<String, List<SubjectsAnswer>>();
		if (subjectsAnswerList != null && subjectsAnswerList.size() > 0) {
			List<String> ids = new ArrayList<String>();
			subjectsAnswerList.forEach(tmp -> {
				ids.add(tmp.getId());
			});
			List<SubjectsAnswer> subjectsAnswerList2 = null;
			if (ids.size() > 0) {
				WherePrams wherePrams2 = Method.where("isDelete", C.EQ, 0);
				wherePrams2.and("status", C.EQ, 2);
				//////////////
				//////////////
				wherePrams2.andIn("subjectId", C.IN, ids);
				//////////////
				//////////////
				subjectsAnswerList2 = subjectsAnswerService.list(wherePrams2);

			}
			

			// 组合一下
			// subjectsAnswerList
			// subjectsAnswerList2
			subjectsAnswerList.forEach(tmp -> {
				///吧ID换为图片URL
				List<FileInfo> imgFiles=null;
				
				if (tmp.getImgs() != null&&tmp.getImgs().length()>5) {
					WherePrams imgPrams = Method.where("isDelete", C.EQ, 0);
					imgPrams.andIn("id", C.IN, arrayStringToList(tmp.getImgs()));
					imgFiles=fileInfoService.list(imgPrams);
				}
				
				
				List<String> imgList=new ArrayList<String>();
				if (imgFiles != null) {
					imgFiles.forEach(one -> {
						imgList.add(filePath+one.getUrl());
					});
					tmp.setImgs(imgList.toString());
				}
				
				///结束
				
				result.put(tmp.getId(), new ArrayList<SubjectsAnswer>());
				result.get(tmp.getId()).add(tmp);
			});
			if (subjectsAnswerList2 != null) {
				subjectsAnswerList2.forEach(tmp -> {
					///吧ID换为图片URL
					List<FileInfo> imgFiles=null;
					
					if (tmp.getImgs() != null&&tmp.getImgs().length()>5) {
						WherePrams imgPrams = Method.where("isDelete", C.EQ, 0);
						imgPrams.andIn("id", C.IN, arrayStringToList(tmp.getImgs()));
						imgFiles=fileInfoService.list(imgPrams);
					}
					
					
					List<String> imgList=new ArrayList<String>();
					if (imgFiles != null) {
						imgFiles.forEach(one -> {
							imgList.add(filePath+one.getUrl());
						});
						tmp.setImgs(imgList.toString());
					}
					
					///结束
					
					
					if (result.keySet().contains(tmp.getSubjectId())) {
						result.get(tmp.getSubjectId()).add(tmp);
					}
				});
			}
		}
		
		List<List<SubjectsAnswer>> result2=new ArrayList<List<SubjectsAnswer>>();
		result.keySet().forEach(tmp->{
			result2.add(result.get(tmp));
		});

		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", result2);
		return obj.toString();
	}
	public static void main(String[] args) {
		List<String> target=new ArrayList<String>();
		target.add("a");
		target.add("b");
		target.add("c");
		target.add("d");
		String s=target.toString();
		System.out.println(s);
		String[] a=s.substring(1, s.length()-1).replace(" ", "").split(",");
		for(String tmp:a) {
			System.out.println(tmp);
		}
	}
	
	/*
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImg(MultipartFile file,String questClassId,String subjectId) {
		
		if(questClassId==null||questClassId.length()<5) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "参数错误", 0);
			return obj.toString();
		}
		
		if(subjectId==null||subjectId.length()<5) {
			ResultObj obj=new ResultObj(ResultCode.RESULT_EXCEPTION, "参数错误", 0);
			return obj.toString();
		}
		
		
		Date now=new Date();
		String dir=DateUtil.dateToString(now, "yyyyMMdd");
		UploadTmp uploadTmp=uploadSingleFile(file,"Quest/"+dir);
		
		
		Map<String,String> data=new HashMap<String,String>();
		data.put("id", uploadTmp.getId());
		data.put("filePath", filePath + uploadTmp.getUrl());
		
		
		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",data);
		return obj.toString();
	}
	*/
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImg(MultipartFile file) {
		
		Date now=new Date();
		String dir=DateUtil.dateToString(now, "yyyyMMdd");
		UploadTmp uploadTmp=uploadSingleFile(file,dir);
		
		
		Map<String,String> data=new HashMap<String,String>();
		data.put("id", uploadTmp.getId());
		data.put("filePath", filePath + uploadTmp.getUrl());
		
		
		ResultObj obj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",data);
		return obj.toString();
	}
	
	public UploadTmp uploadSingleFile(MultipartFile file, String dirs) {
		try {

			// 文件上传路径
			String serverPath = fileUploadPath;

			String uploadDir = "";

			// 文件名称
			String fileName = file.getOriginalFilename();
			// 文件后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (dirs != null && dirs.length() > 0) {
				uploadDir = uploadDir + "/" + dirs + "/" + "avator";
			} else {
				uploadDir = uploadDir + "/" + "avator";
			}

			// 检查目录是否存在
			File dir = new File(serverPath + uploadDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 随机名称
			String randomFileName = UUID.randomUUID().toString();
			// 文件存在服务器上的路径
			String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

			// 将文件上传到文集的物理地址
			File serverFile = new File(serverPath + fileUrl);
			file.transferTo(serverFile);
			log.info("文件上传成功");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("fileUrl", fileUrl);
			map.put("filePath", filePath + fileUrl);
			
			
			FileInfo tmp=new FileInfo();
			tmp.setFileName(randomFileName);
			tmp.setUrl(fileUrl);	
			tmp.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			
			String id=fileInfoService.addLocalByid(tmp);
			
			UploadTmp result=new UploadTmp();
			result.setId(id);
			result.setUrl(fileUrl);
			return result;

		} catch (Exception e) {
			log.error(e.getMessage());
			return null;
		}

	}
	
	private static String getWeekBegin(String date) {
		LocalDate now = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);

		while (DayOfWeek.SUNDAY != now.getDayOfWeek()) {
			now = now.plusDays(-1);
		}

		return now.toString()+" 00:00:00";
	}

	private static String getWeekEnd(String date) {
		LocalDate now = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);

		while (DayOfWeek.SATURDAY != now.getDayOfWeek()) {
			now = now.plusDays(1);
		}
		return now.toString()+" 23:59:59";
	}
	
	private static String getMonthBegin(String date) {
		LocalDate now = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);
		return LocalDate.of(now.getYear(), now.getMonth(), now.lengthOfMonth()).toString()+" 00:00:00";
	}
	private static String getMonthEnd(String date) {
		LocalDate now = LocalDate.parse(date, DateTimeFormatter.ISO_DATE);
		return LocalDate.of(now.getYear(), now.getMonth(), now.lengthOfMonth()).toString()+" 23:59:59";
	}
	private static boolean isPark() {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		return "KFR7HK8INC28IAL3D0568BDB4C4341898018AEBF0DF3E739".equals(sysUser.getRoleId());
	}
	private static boolean isService() {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		return "6RVJFO4KJ5NYPFXY0D363DC54DA44400AA3E45578BDEA99F".equals(sysUser.getRoleId());
	}
	
	
	/**
	 * like [a,b,c,d]
	 * @param s
	 * @return
	 */
	private static List<String> arrayStringToList(String s){
		List<String> result=new ArrayList<String>();
		
		String[] imgs = s.substring(1, s.length() - 1).replace(" ", "").split(",");
		for(String one:imgs) {
			result.add(one);
		}
		
		return result;
	}

	private class UploadTmp{
		private String id;
		private String url;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		
	}
	
	private static class SubjectJsonPojo{
		private String examineType;
		private List<SubjectsHistory> subjects=new ArrayList<SubjectsHistory>();
		public String getExamineType() {
			return examineType;
		}
		public void setExamineType(String examineType) {
			this.examineType = examineType;
		}
		public List<SubjectsHistory> getSubjects() {
			return subjects;
		}
		public void setSubjects(List<SubjectsHistory> subjects) {
			this.subjects = subjects;
		}
		
	}
	
	private static class AnswerVO{
		private QuestAnswerVO questClass;
		private List<SubjectAnswerVO> subjectList;
		
		public QuestAnswerVO getQuestClass() {
			return questClass;
		}
		public void setQuestClass(QuestAnswerVO questClass) {
			this.questClass = questClass;
		}
		public List<SubjectAnswerVO> getSubjectList() {
			return subjectList;
		}
		public void setSubjectList(List<SubjectAnswerVO> subjectList) {
			this.subjectList = subjectList;
		}
		
		
		
		@Override
		public String toString() {
			return "AnswerPojo [questClass=" + questClass.toString() + ", subjectList=" + subjectList.toString() + "]";
		}



			
		}
	
	private static class QuestAnswerVO{
		private String id;
		private int abarbeitung;

		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public int getAbarbeitung() {
			return abarbeitung;
		}
		public void setAbarbeitung(int abarbeitung) {
			this.abarbeitung = abarbeitung;
		}
		@Override
		public String toString() {
			return "QuestAnswerVO [id=" + id + ", abarbeitung=" + abarbeitung + "]";
		}
		
		
		
	}
	private static class SubjectAnswerVO{
		private String id;
		private String options;
		private float score;
		private String imgs;
		private String content;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getOptions() {
			return options;
		}
		public void setOptions(String options) {
			this.options = options;
		}
		public float getScore() {
			return score;
		}
		public void setScore(float score) {
			this.score = score;
		}

		public String getImgs() {
			return imgs;
		}
		public void setImgs(String imgs) {
			this.imgs = imgs;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}
		@Override
		public String toString() {
			return "SubjectAnswerVO [id=" + id + ", options=" + options + ", score=" + score + ", imgs=" + imgs
					+ ", content=" + content + "]";
		}
		
		
		
		
	}
}
